from flask import Flask, jsonify
from captcha.image import ImageCaptcha
import random, string, uuid, base64, io
# import redis

app = Flask(__name__)
# redis_client = redis.Redis(host='localhost', port=6379, db=0)

# 生成加/减法表达式和结果
def generate_math_expression():
    a = random.randint(1, 20)
    b = random.randint(1, 20)
    op = random.choice(['+', '-'])
    if op == "-" and a < b:
        a,b = b, a
    expression = f"{a} {op} {b}"
    result = str(eval(expression))
    return f"{expression} = ?", result

@app.route("/api/captcha", methods=["GET"])
def get_math_captcha():
    expression, answer = generate_math_expression()
    captcha_id = str(uuid.uuid4())
    print(expression)
    image = ImageCaptcha()
    image_data = image.generate(expression)
    image_bytes = io.BytesIO(image_data.read())
    base64_image = base64.b64encode(image_bytes.getvalue()).decode("utf-8")
    image_base64_str = f"data:image/png;base64,{base64_image}"

    # 存答案到 Redis，有效期 5 分钟
    # redis_client.setex(f"captcha:{captcha_id}", 300, answer)

    return jsonify({
        "result": "success",
        "data": {
            "captcha_id": captcha_id,
            # "captcha_img_base64": image_base64_str,
            "expires_in": 300,
            "answer": answer,  # 开发测试时可打开
            "expression": expression
        }
    })

# if __name__ == "__main__":
#     app.run(debug=True)

def test():
    print(">>",__name__)
